import React, { useState } from 'react'
import FoldBoxGroupContext from './context'
import type { FoldBoxProps } from './interface'
import styles from './index.module.less'
import classNames from 'classnames'
import { DownCircleOutlined } from '@ant-design/icons'

const FoldBox: React.FC<FoldBoxProps> = props => {
    const groupContext = React.useContext(FoldBoxGroupContext)
    const groupValue = groupContext?.value

    /** 展开状态 */
    const [expanded, setExpanded] = useState<boolean>(props.expand ?? false)

    /** 切换展开状态 */
    const toggleExpand = () => {
        if (!expanded) {
            groupContext?.onChange(props.value)
        }

        setExpanded(v => !v)
    }

    React.useEffect(() => {
        if (!groupValue) return

        if (props.value === groupValue) {
            setExpanded(true)
        } else {
            setExpanded(false)
        }
    }, [groupValue, props.value])

    return (
        <div
            className={classNames(styles.foldBox_container, props.className)}
            style={{ ...props.style }}
        >
            <div
                className={classNames(styles.foldBox, {
                    [styles.foldBox_expanded]: expanded,
                })}
            >
                <div className={styles.foldBox_header}>
                    {/* 标题 */}
                    <span className={styles.foldBox_header_title}>{props.title}</span>

                    {/* 状态栏 */}
                    {props.statusBar && (
                        <span className={styles.foldBox_header_statusBar}>{props.statusBar}</span>
                    )}
                </div>

                <div className={styles.foldBox_content}>
                    {/* 内容 */}
                    <div className={styles.foldBox_content_container}>{props.children}</div>

                    <div className={styles.foldBox_content_toggle}>
                        <DownCircleOutlined
                            className={classNames({
                                [styles.foldBox_content_toggle_up]: expanded,
                            })}
                            onClick={toggleExpand}
                        />
                    </div>
                </div>
            </div>

            {/* 折叠内容 */}
            {expanded && <div className={styles.foldBox_expand}>{props.expandContent}</div>}
        </div>
    )
}

export default FoldBox
